import scala.sys.process._
import scala.util.matching.Regex
import ui_utils._


object tool_process_killer {
  // regex patterns 
  val pat_title = new Regex("^PID[\\s]+TTY[\\s]+TIME[\\s]+CMD$")
  val pat_process = new Regex("^([\\d]+)[\\s]+[\\w\\W\\d]+[\\s]+[\\d][\\d]:[\\d][\\d]:[\\d][\\d][\\s]+([\\w\\W]+)$")

  def main (argv : Array[String]) {
    // check 
    assert(argv.length == 1, {println("Usage: tool_process_killer process_keyword")}) 

    // acquire process list 
    val pkword = argv(0)
    val ps_command = "ps -u " + ("whoami" !!) 
    val ps_result = ps_command !! 

    val ps_lines = ps_result.split("\n").map(_.trim)
    var pid_pname : Array[(String, String)] = Array()

    // filter the process list based on the keyword 
    for (aline <- ps_lines) {
      aline match {
        case pat_title() => ()
        case pat_process(pid, pname) => {
          if (pname contains pkword) {
            pid_pname = pid_pname :+ (pid, pname)
          }
        }
        case _ => assert(false, {println("Error: Unknown process info: " + aline)})
      }
    }

    // make option list
    var opts : OPT_LIST = new OPT_LIST()
    for (p_n <- pid_pname) {
      opts.AddOption(new OPTION(" (pid: " + p_n._1 + ") " + p_n._2, "kill -9 " + p_n._1))
    }

    // display opts 
    var selecteds = UI_UTILS.DisplayOptions(opts, UI_UTILS.GetIntsFromConsole("Options: "))
    for (asel <- selecteds) {
      opts.RunOption(asel)
    }
  }
}
